<template>
  <el-dialog v-el-drag-dialog class="dialog-pdts" :visible.sync="dialogpdtsvisible" @open="openDialog" @close="closeDialog">
    <h3 slot="title">添加活动商品</h3>
    <!-- 筛选头部 -->
    <div class="filter-box">
      <el-form ref="pdtsFilter" :inline="true" :model="pdtsFilter" class="filter-form">
        <el-form-item>
          <el-input v-model="pdtsFilter.name" size="medium" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="pdtsFilter.category1" size="medium" placeholder="请选择一级分类" @change="getCategory1">
            <el-option v-for="(c1, index) in category1" :key="index" :label="c1.name" :value="c1.parentId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="pdtsFilter.category2" size="medium" placeholder="请选择二级分类" @change="getCategory2">
            <el-option v-for="(c2, index) in category2" :key="index" :label="c2.name" :value="c2.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="pdtsFilter.category3" size="medium" placeholder="请选择三级分类" @change="getCategory3">
            <el-option v-for="(c3, index) in category3" :key="index" :label="c3.name" :value="c3.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="toFilte">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 全选操作栏 -->
    <div v-if="reqPdts.length > 0 && !isradio" class="list-func">
      <el-checkbox v-model="checkedAll" @change="checkAll">全选</el-checkbox>
      <p class="selected-num">已选择 <span>{{ checkedCount }}</span> 项</p>
      <el-button type="text" @click="clearAll">清空</el-button>
    </div>
    <div v-loading="loading" class="table-box">
      <p v-if="reqPdts.length === 0" class="none">您还没有上传商品～</p>
      <table v-else class="pdts-selected-table" align="left" border="0" cellpadding="0" cellspacing="0">
        <thead>
          <tr>
            <th>选择</th>
            <th>序号</th>
            <th>商品名称</th>
            <th>分类</th>
            <th>价格</th>
            <th>库存</th>
            <th>销量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(pdt, index) in reqPdts" :key="index">
            <td v-if="isradio"><el-checkbox v-model="pdt.selected" @change="checkItem(pdt)" /></td>
            <td v-else><el-checkbox v-model="pdt.selected" @change="checkItem" /></td>
            <td>{{ (index + 1 + pageSize * ( currentPage - 1 )) | addZeroPrefix }}</td>
            <td>
              <div>
                <p class="img"><el-image style="width: 80px; height: 80px" :src="qnPath(pdt.image)" fit="fit" /></p>
                <div class="info">
                  <p class="name">{{ pdt.name }}</p>
                  <p class="id">ID：{{ pdt.id }}</p>
                </div>
              </div>
            </td>
            <td>{{ pdt.typeValue }}</td>
            <td>{{ pdt.unitPrice | fixedPrice }}</td>
            <td>{{ pdt.amount }}</td>
            <td>{{ pdt.sales }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 分页 -->
    <div v-if="reqPdts.length > 0" class="pagination">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, sizes, jumper"
        :total="pdtsCount"
        hide-on-single-page
        :page-sizes="[5, 8, 10]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div v-if="reqPdts.length > 0" class="btns">
      <el-button @click="goBack">返 回</el-button>
      <el-button type="primary" @click="OK">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getMdseList, getMdseType } from '@/api/goods';
export default {
  name: 'DialogPdts',
  props: {
    dialogpdtsvisible: {
      type: Boolean,
      default: false
    },
    // eslint-disable-next-line vue/require-default-prop
    selectedlist: {
      type: Array
    },
    shopid: {
      type: String,
      default: ''
    },
    isradio: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      loading: true,
      pdtsFilter: {
        name: '',
        category1: '',
        category2: '',
        category3: '',
        category: ''
      },
      selectedlistBak: [], // 备份传过来的已经确定了的商品
      category1: [],
      category2: [],
      category3: [],
      reqPdts: [],
      reqedPdtsArr: [],
      reqedPdts: [],
      radioSelectedPdt: [], // 单选时被勾选的商品
      checkedAll: false,
      checkedCount: 0,

      // 分页
      currentPage: 1,
      pageSize: 4,
      pdtsCount: 0
    };
  },
  watch: {
    checkedCount(value) {
      let flag = 0;
      this.reqedPdtsArr[this.currentPage - 1].map(pdt => {
        if (pdt.selected) flag++;
      });
      this.checkedAll = value === flag;
    }
  },
  methods: {
    openDialog() {
      this.currentPage = 1;
      this.getMdseList();
      this.getCategory();
      this.checkedCount = this.selectedlist.length;
      this.selectedlistBak = JSON.parse(JSON.stringify(this.selectedlist));
    },
    toFilte() {
      this.currentPage = 1;
      this.getMdseList();
    },
    getCategory() {
      new Promise((resolve, reject) => {
        getMdseType({ level: '1' }).then(res => {
          this.category1 = res.data;
          this.category2 = [];
          this.category3 = [];
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    getCategory1(val) {
      this.pdtsFilter.category1 = val;
      this.pdtsFilter.category2 = '';
      this.pdtsFilter.category3 = '';
      new Promise((resolve, reject) => {
        getMdseType({ parentId: val }).then(res => {
          this.category2 = res.data;
          this.category3 = [];
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    getCategory2(val) {
      this.pdtsFilter.category2 = val;
      this.pdtsFilter.category3 = '';
      new Promise((resolve, reject) => {
        getMdseType({ parentId: val }).then(res => {
          this.category3 = res.data;
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    getCategory3(val) {
      this.pdtsFilter.category3 = val;
    },
    getMdseList(shopId = this.shopid, mdseName = this.pdtsFilter.name, mdsePropertyId = this.pdtsFilter.category, pageNo = this.currentPage, pageSize = this.pageSize) {
      this.loading = true;
      new Promise((resolve, reject) => {
        getMdseList({ shopId, mdseName, mdsePropertyId, pageNo, pageSize }).then(res => {
          this.loading = false;
          const list = res.data.mdse;
          var arr = [];
          list.map(p => {
            p.selected = false;
            arr.push(p);
          });
          this.reqedPdtsArr[this.currentPage - 1] = arr;
          // 勾选已经被选中的商品
          this.selectedlist.forEach(pdt => {
            list.forEach(p => {
              p.selected = p.selected ? p.selected : pdt.id === p.id;
            });
          });
          this.reqPdts = list;
          this.pdtsCount = res.data.size;
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    checkAll(value) {
      this.checkedCount = value ? this.reqPdts.length : 0;
      this.reqPdts.forEach(pdt => {
        pdt.selected = value;
      });
    },
    checkItem(value) {
      if (this.isradio) {
        this.radioSelectedPdt = [];
        this.reqPdts.forEach(ac => {
          ac.selected = false;
        });
        value.selected = true;
        this.radioSelectedPdt.push(value);
      } else {
        value ? this.checkedCount++ : this.checkedCount--;
        this.reqedPdtsArr[this.currentPage - 1] = this.reqPdts;
      }
    },
    clearAll() {
      if (this.checkedCount === 0) return;
      this.checkedCount = 0;
      this.checkedAll = false;
      this.reqedPdtsArr.forEach(arr => {
        arr.forEach(pdt => {
          pdt.selected = false;
        });
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getMdseList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getMdseList();
    },
    goBack() {
      this.pdtsFilter = {
        name: '',
        category1: '',
        category2: '',
        category3: '',
        category: ''
      };
      this.currentPage = 1;
      this.$emit('goBack');
    },
    OK() {
      // eslint-disable-next-line no-undef
      const pdts = _.flattenDeep(this.reqedPdtsArr);
      this.reqedPdts = pdts.filter(p => {
        return p;
      });
      if (this.isradio) {
        this.$emit('ok', this.radioSelectedPdt);
      } else {
        const selectedList = this.reqedPdts.filter(pdt => pdt.selected);
        this.$emit('ok', selectedList);
      }
    },
    closeDialog() {
      this.goBack();
    }
  }
};
</script>
<style lang="scss" scoped>
	.dialog-pdts{
		h3{
			margin: 0;
			color: $textColorDark;
			font-size: $fontSizeLg;
		}
		/deep/ .el-dialog__header{
			border-bottom: 1px solid $borderColor;
		}
		/deep/ .el-dialog__body{
			padding: 15px 20px;
		}
		/deep/ .el-dialog{
			width: 80vw;
			max-width: 1100px;
			max-height: 85vh;
			/* margin-top: 10vh !important; */
		}
		/deep/ .el-form-item{
			max-width: 175px;
			margin-bottom: 15px;
		}
		.table-box{
			overflow-y: scroll;
      max-height: 365px;
      min-height: 300px;
		}
		table{
			width: 100%;
			float: none;
			p{
				margin: 0
			}
			th,td{
				text-align: center;
				color: $textColorDark;
				font-size: $fontSizeBase;
				line-height: 1.58;
				border-bottom: 1px solid $disabledColor;
				border-right: 1px solid $disabledColor;
				width: 12.8%;
				&:first-child{
					border-left: 1px solid $disabledColor;
				}
				&:nth-child(2),&:first-child{
					width: 6.8%;
				}
				&:nth-child(3){
					text-align: left;
					width: 35%;
				}
			}
			th{
				height: 40px;
				line-height: 40px;
				background-color: #F9FBFC;
				border-top: 1px solid $disabledColor;
				&:nth-child(3){
					padding-left: 10px;
				}
			}
			td{
				background-color: #fff;
				padding: 10px 20px;
				&:nth-child(3){
					&>div{
						display: flex;
						align-items: flex-start;
						justify-content: flex-start;
						.info{
							margin-left: 20px;
						}
						.id{
							color: $textColorBase;
							margin-top: 10px;
						}
						.name{
							text-overflow: -o-ellipsis-lastline;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							line-clamp: 2;
							-webkit-box-orient: vertical;
						}
					}
				}
			}
		}
  }
  .none{
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 50vh;
    width: 100%;
  }
	.list-func{
		display: flex;
		align-items: center;
		margin-bottom: 20px;
		.selected-num{
      margin: 0 20px;
      span{
        color: $mainColor
      }
    }
	}
.pagination{
	padding-top: 10px;
	padding-bottom: 10px;
	text-align: center;
	border: 1px solid $borderColor;
	border-top: none;
}.btns{
	padding-top: 15px;
	text-align: center;
}
</style>
